package com.zjc;

import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class Forward {

    private ForwardMsg msg;

    public static void main(String[] args) {
        ForwardMsg cmd = new ForwardMsg(10253, 36253, "127.0.0.1", "CMD 客户端");
        new Thread(() -> new Forward().accept(cmd)).start();

        new Thread(() -> new MessageListener().listening()).start();
    }

    private void accept(ForwardMsg forwardMsg) {
        try {
            System.out.println(forwardMsg.toString());
            this.msg = forwardMsg;
            ServerSocket server = new ServerSocket(forwardMsg.localPort);
            while (true) {
                Socket socket;
                try {
                    socket = server.accept();
                    long ts = System.currentTimeMillis();
                    for (Connect c : MessageListener.vector) {
                        if (ts - c.timestamp > 30000) {
                            close(c);
                        } else {
                            break;
                        }
                    }
                    MessageListener.vector.add(new Connect(socket, this.msg));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {

        }
    }


    public static void close(Closeable... closeables) {
        for (Closeable closeable : closeables) {
            try {
                closeable.close();
            } catch (Exception e) {

            }
        }
    }


}